from typing import Dict, List

from models.models_prod import OpErpSkuMapping
from services.base.biz_service import BizService


class ErpMappingService(BizService):

    def db_config(self) -> dict[str, str]:
        from config.config import CONFIG
        c = CONFIG.get('prod')['mysql']
        return {
            'host': c['host'],
            'port': c['port'],
            'username': c['username'],
            'password': c['password'],
            'database': c['database'],
            'mysql_log': c['log_sql']
        }

    def __init__(self):
        super().__init__(OpErpSkuMapping)

    def get_erp_mapping(self, size=100, session=None) -> Dict[str, str]:
        internal_session = False
        if session is None:
            session = self.get_session()
            internal_session = True

        try:
            erp_mapping = session.query(OpErpSkuMapping).offset(0).limit(size).all()
            return {item.outer_id_erp: item.outer_id for item in erp_mapping}
        finally:
            if internal_session:
                session.close()

    def get_erp_mapping_by_erp_ids(self, erp_ids: List[str], session=None) -> Dict[str, str]:
        internal_session = False
        if session is None:
            session = self.get_session()
            internal_session = True

        try:
            erp_mapping = session.query(OpErpSkuMapping).filter(OpErpSkuMapping.outer_id_erp.in_(erp_ids)).all()
            return dict((item.outer_id_erp, item.outer_id) for item in erp_mapping)
        finally:
            if internal_session:
                print("internal_session")
                session.close()
